<template>
    <div class="xueshengliebiao">
        <div>
            <a-button type="primary" class="editable-add-btn" @click="handleAdd">
            +新增学生
            </a-button>
            <a-upload
                v-show="true"
                name="file"
                :multiple="false"
                @change="changeFile"
                :customRequest="customRequest"
                >
                    <a-button  class="editable-add-btn">
                    批量导入
                    </a-button>
            </a-upload>

            <a-input-search
                v-model="searchValue"
                placeholder="input search text"
                enter-button
                style="width: 300px"
                @search="onSearch(searchValue)"
            />
            <div class="chooseClass">
                <a-tabs default-active-key="0" @change="callback">
                <a-tab-pane v-for="item,index in classList" :key="index" :tab="item.name" >
                    <a-table bordered :data-source="dataSource" :columns="columns">
                        <template slot="name" slot-scope="text, record">
                            <editable-cell :text="text" @change="onCellChange(record.key, 'name', $event)" />
                        </template>
                        <template slot="email" slot-scope="text, record">
                            <editable-cell :text="text" @change="onCellChange(record.key, 'email', $event)" />
                        </template>
                        <template slot="class" slot-scope="text, record">
                            <editable-cell :text="text" @change="onCellChange(record.key, 'class', $event)" />
                        </template>
                        <template slot="nickclassnumber" slot-scope="text, record">
                            <editable-cell :text="text" @change="onCellChange(record.key, 'nickclassnumber', $event)" />
                        </template>
                        <template slot="operation" slot-scope="text, record">
                            <a-popconfirm
                            v-if="dataSource.length"
                            title="Sure to delete?"
                            @confirm="deleteS(record.key)"
                            >
                            <a href="javascript:;">删除&nbsp;</a>
                            </a-popconfirm>
                            <a-popconfirm
                            v-if="dataSource.length"
                            title="Sure to add?"
                            @confirm="add(record.key)"
                            >
                            <a href="javascript:;">&nbsp; &nbsp; &nbsp;保存增加</a>
                            </a-popconfirm>
                            <a-popconfirm
                            v-if="dataSource.length"
                            title="Sure to modify?"
                            @confirm="modify(record)"
                            >
                            <a href="javascript:;">&nbsp; &nbsp; &nbsp;保存修改</a>
                            </a-popconfirm>
                        </template>
                    </a-table>
                </a-tab-pane>
                </a-tabs>
            </div>
        </div>
        <a-modal
            v-model="modalVisible"
            title="上传中，请稍后"
            centered
            @ok="() => (modalVisible = false)"
            >
            <img src="/imgs/loading.gif" alt="">
        </a-modal>
    </div>
</template>

<script>
import EditableCell from './EditableCell'

export default {
    components:{
        EditableCell,
    },
   mounted() {
        this.axios.defaults.headers.common['Authorization'] = window.sessionStorage.getItem('token');

        (async () => {
            // 获取班级列表
        await   this.axios.post('/user/query_group/').then((res)=>{
                    // console.log(res)
                    this.classList =  res
                    this.className = this.classList[0].name
                });
        //获取班级人员
        await   this.axios.post('/user/query_group_member/',{
                    name:this.classList[0].name
                }).then((res)=>{
                    // console.log(res)
                    this.dataSource =  res
                    this.count = this.dataSource.length +1 
                });

        
        })();
    },
    data() {
        return {
            searchValue:'',
            dataSource:[],
            classList:[],
            className:'',
            classNo:0,
            modalVisible:false,//全屏弹框
            // dataSource: [
            // {
            // key: '0',
            // name: '欧阳欣',
            // account: '2020110780',
            // email: '123@163.com',
            // class: '2021秋季一班',
            // nickclassnumber: '2020110702',
            // password:'123456'
            // },
            // {
            // key: '1',
            // name: '李想',
            // account: '2020110779',
            // email: '456@163.com',
            // class: '2021秋季一班',
            // nickclassnumber: '2020110702',
            // password:'123456'
            // },
            // ],
            count: 2,
            columns: [
                {
                title: '姓名',
                dataIndex: 'name',
                scopedSlots: { customRender: 'name' },
                },
                {
                title: '账号(学工号)',
                dataIndex: 'account',
                },
                {
                title: '邮箱',
                dataIndex: 'email',
                scopedSlots: { customRender: 'email' },
                },
                {
                title: '课程班级',
                dataIndex: 'class',
                scopedSlots: { customRender: 'class' },
                },
                {
                title: '实际班级',
                dataIndex: 'nickclassnumber',
                scopedSlots: { customRender: 'nickclassnumber' },
                },
                {
                title: '操作',
                dataIndex: 'operation',
                scopedSlots: { customRender: 'operation' },
                },
            ],
        }
    },
    methods: {
            onCellChange(key, dataIndex, value) {
            const dataSource = [...this.dataSource];
            const target = dataSource.find(item => item.key === key);
            if (target) {
                target[dataIndex] = value;
                this.dataSource = dataSource;
            }
            },
            onDelete(key) {
            const dataSource = [...this.dataSource];
            this.dataSource = dataSource.filter(item => item.key !== key);
            },
            handleAdd() {
            const { count, dataSource } = this;
            const newData = {
                key: count,
                name: `name${count}`,
                account: 'account',
                email: `email`,
                class:'class',
                nickclassnumber:`nickclassnumber`,
            };
            this.dataSource = [...dataSource, newData];
            this.count = count + 1;
            },
            deleteS(key){
                let username = ''
                this.dataSource.forEach((item) => {
                    if(item.key ==key){
                        username = item.account
                    }
                });
                this.axios.post('/user/delete_group_member/',{
                    username:username
                }).then(()=>{
                    this.axios.post('/user/query_group_member/',{
                    name:this.classList[this.classNo].name
                    }).then((res)=>{
                    this.dataSource =  res
                    this.count = this.dataSource.length +1 
                });
                })
            },
            add(key){
                console.log(key)
                this.axios.post('/user/add_group_member/',{
                name:this.className,
                username:this.dataSource[key-1].account,
                nickname:this.dataSource[key-1].name,
                nickclassnumber:Number(this.dataSource[key-1].nickclassnumber)  ,
                email:this.dataSource[key-1].email,
                }).then((res)=>{
                    console.log(res)
                    this.$message.info('增加成功')
                })
            },
            modify(data){
                console.log(data)
                this.axios.post('user/modify_info/',{
                    username: data.account ,
                    email: data.email ,
                    name: data.name ,
                }).then(()=>{
                    this.$message.success('修改成功')
                })
            },

            onSearch(searchValue){
                this.axios.post('/user/search_group_member/',{
                    name:this.className,
                    string:searchValue,
                }).then((res)=>{
                    this.dataSource =  res
                })
            },
            callback(key) {
                this.className = this.classList[key].name
                this.classNo = key
                this.getClassMember(key)
            },
            //获取班级人员
            getClassMember(index){
                this.axios.post('/user/query_group_member/',{
                    name:this.classList[index].name
                }).then((res)=>{
                    console.log(res)
                    this.dataSource =  res
                })
            },
            // 批量导入
            changeFile(info) { // 上传文件
            if (info.file.status !== 'uploading') {
            console.log(info.file, info.fileList);
            }
            if (info.file.status === 'done') {
            this.$message.success(`${info.file.name} 上传成功`);
            } else if (info.file.status === 'error') {
            this.$message.error(`${info.file.name} 上传失败.`);
            }
            },
            customRequest(data){ // 上传提交
                const formData = new FormData() 
                formData.append('file', data.file)
                formData.append('name', this.className)
                console.log(data)
                // console.log('_data'+_data)
                this.modalVisible = true
                this.saveFile(formData)

            },
            deliverKey(data){
                this.key = data.key
                console.log(this.key)
            },
            saveFile (formData) {
                this.axios({
                method: 'post',
                url: '/user/add_group_members/',
                headers: {
                },
                params:{
                },
                data: formData
                }).then((response) => {
                    console.log(response)
                    this.modalVisible = false
                    this.$message.success('上传成功！')
                    this.getClassMember(this.classNo)
                }).catch(function (error) {
                    console.log(error)
                })
            },
            
    },
}
</script>

<style lang="scss">
    .xueshengliebiao{
        .editable-cell {
        position: relative;
        }

        .editable-cell-input-wrapper,
        .editable-cell-text-wrapper {
        padding-right: 24px;
        }

        .editable-cell-text-wrapper {
        padding: 5px 24px 5px 5px;
        }

        .editable-cell-icon,
        .editable-cell-icon-check {
        position: absolute;
        right: 0;
        width: 20px;
        cursor: pointer;
        }

        .editable-cell-icon {
        line-height: 18px;
        display: none;
        }

        .editable-cell-icon-check {
        line-height: 28px;
        }

        .editable-cell:hover .editable-cell-icon {
        display: inline-block;
        }

        .editable-cell-icon:hover,
        .editable-cell-icon-check:hover {
        color: #108ee9;
        }

        .editable-add-btn {
        margin-left: 18px;
        margin-bottom: 30px;
        margin-right: 20px;
        }
        .editable-add-btn:nth-child(2){
            margin-right: 580px;
        }
        .ant-upload-list{
            display: none;
        }
    }
</style>